import * as PIXI from 'pixi.js'
import { PixiComponent } from '@inlet/react-pixi'

const onClick = (callback, instance) => (event) => {
  const position = event.data.getLocalPosition(instance)
  callback(position.x, position.y)
}

const onPointerMove = (callback, instance) => (event) => {
  const position = event.data.getLocalPosition(instance)
  callback(position.x, position.y)
}

export default PixiComponent('Tough_layer', {
  create: ({ width, height }) => {
    const layer = new PIXI.Container()
    layer.interactive = true
    layer.hitArea = new PIXI.Rectangle(0, 0, width, height)
    return layer
  },
  didMount: () => {},
  willUnmount: () => {},
  applyProps: (instance, oldProps, newProps) => {
    const {
      action, move, width, height,
    } = newProps
    if (oldProps.width !== width || oldProps.height !== height) {
      instance.hitArea = new PIXI.Rectangle(0, 0, width, height)
    }
    if (action) {
      instance.removeAllListeners(['pointerdown'])
      instance.on('click', onClick(action, instance))
      if (move) {
        instance.on('pointermove', onPointerMove(move, instance))
      }
    } else {
      instance.interactive = false
    }
  },
})
